<template>
	<view class="body">
		<!-- 循环遍历所有单据 -->
		<view v-for="(doc, docIndex) in listData" :key="docIndex" class="document-container">
			<!-- 单据头部信息 -->
			<view class="top-container">
				<uni-list :border="false">
					<uni-list-item :border="false" title="单据编号" :rightText="doc.master.billNo" />
					<uni-list-item :border="false" title="汇报人" :rightText="doc.master.prtUser" />
					<uni-list-item :border="false" title="车间名称" :rightText="doc.master.workShopName" />
					<uni-list-item :border="false" title="生产订单号" :rightText="doc.master.prdBillNo" />
					<uni-list-item :border="false" title="日期">
						<template v-slot:footer>
							<uni-dateformat 
							  :date="doc.master.date" 
							  format="yyyy年MM月dd日" 
							  style="font-size: 20px; color: #000000;"
							></uni-dateformat>
						</template>
					</uni-list-item>
				</uni-list>
			</view>

			<!-- 单据明细信息 - 折叠展开样式 -->
			<view class="detail-container">
				<view v-for="(detail, detailIndex) in doc.details" :key="detailIndex" class="detail-item">
					<view class="collapse-header" @click="toggleDetail(docIndex, detailIndex)">
						<view class="header-left">
							<text class="material-name">{{ '物料名称:' }}{{ detail.materialName }}</text>
							<text class="material-name">{{ '物料编码:' }}{{ detail.materialNo }}</text>
							<text class="quantity">{{ '合格数量  ' }} {{ detail.quaQty }} {{ detail.unit || '件' }}</text>
						</view>
						<uni-icons :type="detail.expanded ? 'arrowup' : 'arrowdown'" size="18" color="#666"></uni-icons>
					</view>
					
					<view class="collapse-content" v-if="detail.expanded">
						<uni-list :border="false">
							<uni-list-item :border="false" title="物料名称" :rightText="detail.materialName" />
							<uni-list-item :border="false" title="物料编号" :rightText="detail.materialNo" />
							<uni-list-item :border="false" title="规格" :rightText="detail.specification" />
							<uni-list-item :border="false" title="工序号" :rightText="detail.operpNo.toString()" />
							<uni-list-item :border="false" title="工序说明" :rightText="detail.describtion" />
							<uni-list-item :border="false" title="合格数量" :rightText="detail.quaQty.toString()" />
							<uni-list-item :border="false" title="工废数量" :rightText="detail.processFailQty.toString()" />
							<uni-list-item :border="false" title="料废数量" :rightText="detail.materialFailQty.toString()" />
							<uni-list-item :border="false" title="完工数量" :rightText="detail.endQty.toString()" />
							<uni-list-item :border="false" title="操作员" :rightText="detail.operator" />
							<uni-list-item :border="false" title="工时"  :rightText="detail.workTime.toString()" />
							<uni-list-item :border="false" title="操作员" :rightText="detail.operator" />
							<uni-list-item>
								<template v-slot:header>
								  <text style="font-size: 18px;">不合格数量</text>
								</template>
								<template v-slot:footer>
								  <uni-easyinput v-model="detail.unQuaqty" type="number" 
								  @input="handleunquaqty(detail)"
								  placeholder="请输入不合格数量" />
								</template>
							</uni-list-item>
						</uni-list>
					</view>
					<view>
						<button @click="auditInspect(doc)" class="footerBtn" ><i
								class="iconfont icon-duihao btn_icon" ></i>审核
						</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import uniTransition from 'uni_modules/uni-transition/components/uni-transition/uni-transition.vue';
	import uniEmptyInfo from "../../vBase/components/uni-empty-info/uni-empty-info.vue"
	import {
		getOptrptisDetail,
		auditReport
	} from '@/utils/api.js'
	import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'

	export default {
		components: {
			uniIcons
		},
		data() {
			return {
				listData: [] // 存储所有单据数据
			}
		},

		onLoad(options) {
			try {
				this.billNo = options.billNo
				this.moBillNo = options.moBillNo
				this.operNo = options.operNo
				this.getOptrptisDetail()
			} catch (e) {
				uni.showToast({
					title: "加载失败",
					icon: "none"
				})
			}
		},
		methods: {
			//填写不合格数量
			handleunquaqty(e) {
			  let val = e.unQuaqty;
			  // 第一步：清除非法字符，只保留数字和小数点
			  val = val.toString().replace(/[^0-9.]/g, '');
			
			  // 第二步：只保留一个小数点
			  const dotIndex = val.indexOf('.');
			  if (dotIndex !== -1) {
			    val = val.substring(0, dotIndex + 1) + val.substring(dotIndex + 1).replace(/\./g, '');
			  }
			
			  // 第三步：限制为最多两位小数
			  if (val.includes('.')) {
			    val = val.replace(/^(\d+)\.(\d{0,2}).*$/, '$1.$2');
			  }
			
			  // 第四步：处理前导0（只能是0或者0.xx）
			  if (val.startsWith('0') && !val.startsWith('0.') && val.length > 1) {
			    val = val.replace(/^0+/, '') || '0';
			  }
			
			  // 第五步：转为数字用于比较
			  const numeric = parseFloat(val || '0');
			  const mustQty = parseFloat(e.endQty || '0');
			
			  if (numeric <= mustQty) {
			    // 合法，赋值（保留格式化后的字符串）
			    this.$nextTick(() => {
			      e.unQuaqty = val || '0';
			    });
			  } else {
			    // 超过上限，提示并置为 0
			    uni.showToast({
			      title: '不合格数量不能大于完工数量',
			      icon: 'none'
			    });
			    e.unQuaqty = '0';
			  }
			},
			//审核工序汇报单
			auditInspect(doc){
				auditReport(doc).then(res => {
					if (res.data.status === 200){
						uni.showToast({
							title:'审核成功',
							icon:'none'
						})
						setTimeout(() =>{
							uni.navigateBack({
								delta:1
							})
						},2500)
					}
				})
			},
			initData() {
				
			},
			getOptrptisDetail(){
				getOptrptisDetail({
					billNo: this.billNo,
					moBillNo: this.moBillNo,
					operNo: this.operNo
				}).then(res => {
					if (res.statusCode === 200) {
						// 添加折叠状态字段
						const data = res.data.data.data || [];
						data.forEach(doc => {
							doc.details.forEach(detail => {
								detail.expanded = false; // 默认折叠
							});
						});
						this.listData = data;
					} else {
						const errorMsg = res.data?.msg || `请求失败，状态码: ${res.statusCode}`
						uni.showToast({
							title: errorMsg,
							icon: 'none',
							duration: 3000
						})
					}
				}).catch(err => {
					const statusCode = err.statusCode || '未知'
					const errorMsg = err.message || `请求异常: 状态码 ${statusCode}`
					uni.showToast({
						title: errorMsg,
						icon: 'none',
						duration: 3000
					})
				})
			},
			// 切换明细项的展开/折叠状态
			toggleDetail(docIndex, detailIndex) {
				this.listData[docIndex].details[detailIndex].expanded = 
					!this.listData[docIndex].details[detailIndex].expanded;
					
				// 使用$set确保响应式更新
				this.$set(this.listData[docIndex].details, detailIndex, 
					{...this.listData[docIndex].details[detailIndex]});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "../../static/css/common";
	/* 调整列表项左右文字大小 */
	::v-deep .uni-list-item__content-title {
	    font-size: 20px !important;  /* 左侧标题字体大小 */
		padding-left: 5px;
	}
	 
	::v-deep .uni-list-item__extra-text {
	    font-size: 20px !important;  /* 右侧内容字体大小 */
		padding-right: 5px;
		 color: #333;
	}
	 
	/* 调整行间距 */
	::v-deep .uni-list-item__container {
	    padding: 3px 0 !important;   /* 减小上下内边距 */
	    min-height: 10px !important; /* 减小最小高度 */
	}
	/* 新增placeholder-class的样式 */
	.placeholder-style {
	    font-size: 20px !important;
	    color: #999 !important;
	}
	.document-container {
		margin-bottom: 30px;
		border: 1px solid #eee;
		border-radius: 8px;
		padding: 15px;
		background-color: #fff;
		box-shadow: 0 2px 5px rgba(0,0,0,0.1);
	}
	
	.detail-container {
		margin-top: 20px;
	}
	
	.detail-item {
		margin-top: 10px;
		border-radius: 6px;
		border: 1px solid #eee;
		overflow: hidden;
	}
	
	.footerBtn{
		height: 50px;
		border-radius: 4px;
		align-items: center;
		  font-size: 20px;
		background-color: #007AFF;
		box-shadow: 0 0 5px rgba(201, 201, 201, 0.5);
		color: #fff;
	}
	
	.collapse-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		background-color: #f0f7ff;
		cursor: pointer;
		border-left: 3px solid #007AFF;
		transition: background-color 0.3s;
		
		&:active {
			background-color: #e1f0ff;
		}
		
		.header-left {
			display: flex;
			flex-direction: column;
			
			.material-name {
				font-size: 18px;
				font-weight: bold;
				margin-bottom: 5px;
			}
			
			.quantity {
				font-size: 16px;
				color: #343434;
			}
		}
	}
	
	.collapse-content {
		background-color: #f9f9f9;
		padding: 10px 15px;
	}
</style>